import { createStore } from 'vuex'


// 创建一个新的 store 实例
const store = createStore({
  state() {
    return {
      cart: [
        {
          id: 1,
          prize: 10,
          number: 1,
          selected: false
        },
        {
          id: 2,
          prize: 20,
          number: 1,
          selected: false
        },
        {
          id: 3,
          prize: 30,
          number: 1,
          selected: false
        }
      ]
    }
  },
  mutations: {
    increment(state, payload) {
      state.cart = state.cart.map((item) => {
        if (item.id === payload && item.number < 9) {
          item.number += 1
        }
        return item
      })
    },
    decrement(state, payload) {
      state.cart = state.cart.map((item) => {
        if (item.id === payload && item.number > 1) {
          item.number -= 1
        }
        return item
      })
    },
    select(state, payload) {
      state.cart = state.cart.map((item) => {
        if (item.id === payload) {
          item.selected = !item.selected
        }
        return item
      })
    },
    seletAll(state, payload) {
      state.cart = state.cart.map((item) => {
        item.selected = payload;
        return item
      })
    }
  },
  getters: {
    caculateAll: ({ cart }) => {
      let data = cart.filter(item => {
        return item.selected
      })
      data = data.reduce((prev, next) => {
        return prev += next.prize * next.number;
      }, 0)
      return data
    },
  }
})

export default store;